package com.lottery.game.controller.v2.manager;

import com.lottery.game.common.Response;
import com.lottery.game.common.constants.GameConstants;
import com.lottery.game.common.exception.BaseException;
import com.lottery.game.constants.RespErrorCodes;
import com.lottery.game.controller.v2.bet.request.RestartRoomRequest;
import com.lottery.game.core.modules.entity.game.GameRoom;
import com.lottery.game.core.modules.entity.user.GameIssue;
import com.lottery.game.core.modules.service.app.BetService;
import com.lottery.game.core.modules.service.app.UpAndDownReportService;
import com.lottery.game.model.FeedbackRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;

/**
 * @author : yinlin
 * @version : 1.0
 * @date : 2019-02-27 12:18
 * @Description :
 * @Copyright : Copyright (c) 2018
 * @Company : KeRuYun Technology(Beijing) Chengdu Co. Ltd.
 * @link : com.runshang.apps.cloudgame.controller.v2.manager.ManagerCallbackController
 */
@RestController
@RequestMapping(value="/api/v2/manager/callback")
@Api(tags="管理后台-回调接口相关---> 注释 ")
@Slf4j
public class ManagerCallbackController {

    @Autowired
    private UpAndDownReportService upAndDownReportService;

    @Autowired
    private BetService betService;

    private static final String SIGN_KEY = "callback-manager-sign";

//    /**
//     * 上下分是否通过反馈 - 推送Ws消息给前端
//     * @return
//     */
//    @SuppressWarnings("unchecked")
//    @ApiOperation(value = "上下分反馈", notes = "上下分反馈", httpMethod="POST")
//    @PostMapping(value = "/callback/of/up/or/down", produces= {MediaType.APPLICATION_JSON_UTF8_VALUE})
//    @ResponseBody
//    private Response callbackOfUpOrDown(
//            @ApiParam(name = "上下分反馈请求", value = "传入json格式", required = true)
//            @RequestBody FeedbackRequest request) {
//        if (!request.getSign().equals(SIGN_KEY)) {
//            throw new BaseException("非法操作！");
//        }
//        try {
//            String userId = request.getUserId();
//            Boolean result = Boolean.valueOf(request.getResult());
//            String balanceStr = request.getBalance();
//            BigDecimal balance = null;
//            if (!StringUtils.isEmpty(balanceStr)) {
//                balance = BigDecimal.valueOf(Double.valueOf(request.getBalance()));
//            }
//            upAndDownReportService.upAndDownFeedbaakPublish(userId,result,balance);
//            return Response.buildSuccess();
//        } catch (Exception e){
//            log.error(RespErrorCodes.UNKNOWN_ERROR.errorCode(), e);
//            return Response.buildError("操作失败!稍后再试");
//        }
//    }


    /**
     * 重启房间
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @ApiOperation(value = "重启房间", notes = "重启房间", httpMethod="POST")
    @ApiResponses(value = { @ApiResponse(code = 0, message = "", response=Response.class) })
    @PostMapping(value="/restartRoom", produces= {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Response<String> restartRoom(@RequestBody RestartRoomRequest request) {

        Integer initTimeInt = null;

        try {
            Integer.valueOf(request.getExpect());
            initTimeInt = Integer.valueOf(request.getInitTime());
        } catch (Exception e) {
            log.error(RespErrorCodes.PARAM_EXPECT_TYPE_ERROR.errorCode(), e);
            return Response.buildError(RespErrorCodes.PARAM_EXPECT_TYPE_ERROR.getErrorMsg());
        }

        try {
            if(initTimeInt!=null) {

                //构建新的线程
                GameRoom room = new GameRoom();
                room.setRoomLotteryTicketType(request.getRoomTypeId());
                GameRoom roomType = betService.queryRoomType(room);

                //重启房间
                //如果有正在运行的相同期号，进行时间更新
                int changeSecond = initTimeInt;
                if(roomType != null) {
                    changeSecond = initTimeInt + roomType.getDuration();
                }
                //开奖时间为004期理论的开奖时间即 当前之间+210秒+提前封盘时间-游戏时间
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.SECOND, changeSecond);
                GameIssue gameIssue = new GameIssue();
                gameIssue.setIssueApi(request.getExpect());
                gameIssue.setStatus(GameConstants.GameIssueStatus_Running);
                Date openTime = calendar.getTime();
                gameIssue.setOpenTime(openTime);
                betService.tryUpdateIssueOpenTime(gameIssue);
            }
            return Response.build("重新启动成功");
        } catch (Exception e) {
            log.error("重启房间发生错误", e);
            return Response.buildError(RespErrorCodes.UNKNOWN_ERROR.getErrorMsg());
        }
    }
}
